# -*- coding: utf-8 -*-
"""
@Project ：weather 
@File    ：push.py
@Author: guzain
@Date:  2025/7/7 11:30:03
@Email： GZA5210@163.com
@Description: 
"""
import smtplib
import time
import hmac
import hashlib
import base64
import requests
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from serverchan_sdk import sc_send

from services.weather_splicing import Splicing_text_data as Splicing_data, Splicing_html_data
from config.config import SENDKEY, EMAIL, EMAIL_PASSWORD, SMTP_SERVER, SMTP_PORT, WECHAT_WORK_WEBHOOK, DINGTALK_WEBHOOK, DINGTALK_SECRET
from utils.log_config import logger


# Server酱消息推送APP
def ServerChan_Push(music_content, music_name, lz_ch, lz_en, love):
    try:
        title = '🔔查收天气情况🌟'
        response = sc_send(SENDKEY, title, f"{Splicing_data(music_content, music_name, lz_ch, lz_en, love)}", {"tags": "天气预报"})
        if response.get("message") == "SUCCESS":
            logger.info("Server酱消息推送成功!")
        else:
            logger.error("Server酱消息推送失败!")
    except Exception as e:
        logger.error(f"Server酱消息推送失败!,失败原因: {e}", exc_info=True)


# 发送邮件
def Send_Email(to_email, music_content, music_name, lz_ch, lz_en, love):
    subject = Header('🔔查收天气情况🌟', 'utf-8').encode()  # 邮件标题
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = EMAIL
    msg['To'] = to_email
    msg['Subject'] = subject
    # 添加邮件正文
    try:
        # 使用新的Splicing_html_data函数生成HTML内容
        html_content = Splicing_html_data(music_content, music_name, lz_ch, lz_en, love)
        msg.attach(MIMEText(html_content, 'html', 'utf-8'))
    except Exception as e:
        logger.error(f"生成邮件内容失败: {e}", exc_info=True)
        return

    try:
        logger.info(f"正在连接SMTP服务器: {SMTP_SERVER}:{SMTP_PORT}")
        # 连接到SMTP服务器
        server = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, timeout=10)  # 添加超时设置
        logger.info(f"成功连接到SMTP服务器: {SMTP_SERVER}:{SMTP_PORT}")
        
        # 登录到SMTP服务器
        server.login(EMAIL, EMAIL_PASSWORD)
        logger.info("成功登录SMTP服务器")

        # 发送邮件
        server.sendmail(EMAIL, to_email, msg.as_string())
        server.quit()
        logger.info("邮件投递成功!")
    except smtplib.SMTPConnectError as e:
        logger.error(f"连接SMTP服务器失败: {e}", exc_info=True)
    except smtplib.SMTPAuthenticationError as e:
        logger.error(f"SMTP服务器认证失败: {e}", exc_info=True)
    except smtplib.SMTPException as e:
        logger.error(f"SMTP服务器错误: {e}", exc_info=True)
    except Exception as e:
        logger.error(f"邮件投递失败,失败原因: {e}, 类型: {type(e).__name__}", exc_info=True)


# 企业微信推送

def WechatWork_Push(music_content, music_name, lz_ch, lz_en, love):
    try:
        if not WECHAT_WORK_WEBHOOK:
            logger.info("企业微信机器人webhook未配置，跳过推送")
            return
        
        title = '🔔查收天气情况🌟'
        content = Splicing_data(music_content, music_name, lz_ch, lz_en, love)
        
        # 构建企业微信消息体
        data = {
            "msgtype": "text",
            "text": {
                "content": f"{title}\n\n{content}"
            }
        }
        
        response = requests.post(WECHAT_WORK_WEBHOOK, json=data, timeout=10)
        result = response.json()
        
        if result.get("errcode") == 0:
            logger.info("企业微信消息推送成功!")
        else:
            logger.error(f"企业微信消息推送失败: {result}")
    except Exception as e:
        logger.error(f"企业微信消息推送失败!,失败原因: {e}", exc_info=True)


# 钉钉推送

def DingTalk_Push(music_content, music_name, lz_ch, lz_en, love):
    try:
        if not DINGTALK_WEBHOOK:
            logger.info("钉钉机器人webhook未配置，跳过推送")
            return
        
        title = '🔔查收天气情况🌟'
        content = Splicing_data(music_content, music_name, lz_ch, lz_en, love)
        
        # 构建钉钉消息体
        data = {
            "msgtype": "text",
            "text": {
                "content": f"{title}\n\n{content}"
            }
        }
        
        # 处理加签
        if DINGTALK_SECRET:
            timestamp = str(round(time.time() * 1000))
            secret = DINGTALK_SECRET
            secret_enc = secret.encode('utf-8')
            string_to_sign = f"{timestamp}\n{secret}"
            string_to_sign_enc = string_to_sign.encode('utf-8')
            hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
            sign = base64.b64encode(hmac_code).decode('utf-8')
            url = f"{DINGTALK_WEBHOOK}&timestamp={timestamp}&sign={sign}"
        else:
            url = DINGTALK_WEBHOOK
        
        response = requests.post(url, json=data, timeout=10)
        result = response.json()
        
        if result.get("errcode") == 0:
            logger.info("钉钉消息推送成功!")
        else:
            logger.error(f"钉钉消息推送失败: {result}")
    except Exception as e:
        logger.error(f"钉钉消息推送失败!,失败原因: {e}", exc_info=True)